package com.hue.gulimailssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @author 姚凤桥
 * @Date 2021/11/29 11:08
 * @Description:
 */
@Controller
public class LoginController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("token") String token) {
        String userInfo = redisTemplate.opsForValue().get(token);
        return userInfo;
    }

    /**
     * 跳转到登录页面
     *
     * @param redirectUrl
     * @return
     */
    @GetMapping("/login.html")
    public String login(@RequestParam(value = "redirectUrl", required = false) String redirectUrl,
                        Model model, @CookieValue(value = "sso-token", required = false) String ssoToken) {
        if (!StringUtils.isEmpty(ssoToken) && !StringUtils.isEmpty(redirectUrl)) {
            //用户在其他系统已经登录过,跳回到redirectUrl
            return "redirect:" + redirectUrl + "?token=" + ssoToken;
        }

        model.addAttribute("redirectUrl", redirectUrl);
        return "login";
    }

    /**
     * 执行登录请求
     */
    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String redirectUrl, HttpServletResponse response) {

        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            if (!StringUtils.isEmpty(redirectUrl)) {
                String token = UUID.randomUUID().toString().replace("-", "");
                redisTemplate.opsForValue().set(token, username);
                //向登录系统的cookie中添加sso-token,以后每次来到登录系统请求都会携带这个token,以此来判断用户在其他系统是否登录过
                response.addCookie(new Cookie("sso-token", token));
                return "redirect:" + redirectUrl + "?token=" + token;
            }
        }

        return "redirect:/login.html?redirect:" + redirectUrl;
    }
}
